<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form :inline="true" v-show="showSearch" label-width="120px" :label-position="isPhone ? 'top' : 'left'">
          <el-form-item label="标题">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="年份">
            <el-input
              v-model="queryParams.yearNum"
              placeholder="请输入年份"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              :loading="exportLoading"
              :disabled="exportLoading"
              >导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="handleGetList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="list"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="编号"
            align="center"
            key="id"
            prop="id"
            v-if="columns[0].visible"
            width="80"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="标题"
            align="center"
            key="title"
            prop="title"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="年份"
            align="center"
            key="yearNum"
            prop="yearNum"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="开始时间"
            align="center"
            key="startTime"
            prop="startTime"
            v-if="columns[3].visible"
            width="180"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="结束时间"
            align="center"
            key="endTime"
            prop="endTime"
            v-if="columns[4].visible"
            width="180"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="状态"
            align="center"
            key="status"
            prop="status"
            v-if="columns[5].visible"
          >
            <template #default="scope">
              <el-tag :type="scope.row.status === 'enable' ? 'success' : 'info'">
                {{ scope.row.status === 'enable' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            key="remark"
            prop="remark"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="附件"
            align="center"
            key="fileObjects"
            v-if="columns[7].visible"
            width="200"
          >
            <template #default="scope">
              <div v-if="scope.row.fileObjects && scope.row.fileObjects.length > 0" class="file-list">
                <el-link
                  v-for="(file, index) in scope.row.fileObjects"
                  :key="index"
                  :underline="false"
                  @click="handleFileDownload(file)"
                  type="primary"
                  style="margin-right: 8px; display: inline-block;"
                >
                  <el-icon><Document /></el-icon>
                  {{ getFileNameFromPath(file.filePath || file.url || file) }}
                </el-link>
              </div>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleGetList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :label-position="isPhone ? 'top' : 'left'"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="年份" prop="yearNum">
          <el-input
            v-model="form.yearNum"
            placeholder="请输入年份"
            clearable
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="enable">启用</el-radio>
            <el-radio label="disable">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="附件" prop="fileObjects">
          <file-upload
            v-model="form.fileObjects"
            ref="fileUploadRef"
            :limit="20"
            :fileSize="100"
            :fileType="[
              'pdf',
              'doc',
              'docx',
              'xls',
              'xlsx',
              'ppt',
              'pptx',
              'zip',
              'rar',
              '7z',
              'jpg',
              'jpeg',
              'png',
            ]"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SignTime">
import {
  getList,
  delItem,
  addItem,
  editItem,
  getDetail,
} from "@/api/sign-time";
import { isPhone } from "@/utils/index";
import FileUpload from "@/components/FileUpload/index.vue";
import { downloadFile, getFileNameFromPath } from "@/utils/fileDownload";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();

const list = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const open = ref(false);

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `标题`, visible: true },
  { key: 2, label: `年份`, visible: true },
  { key: 3, label: `开始时间`, visible: true },
  { key: 4, label: `结束时间`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `备注`, visible: true },
  { key: 7, label: `附件`, visible: true },
]);

const getDefaultForm = () => ({
  id: undefined,
  title: undefined,
  yearNum: undefined,
  startTime: undefined,
  endTime: undefined,
  remark: undefined,
  status: "enable",
  fileObjects: [],
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    yearNum: undefined,
  },
  form: getDefaultForm(),
  rules: {
    title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
    yearNum: [{ required: true, message: "年份不能为空", trigger: "blur" }],
    startTime: [{ required: true, message: "开始时间不能为空", trigger: "change" }],
    endTime: [{ required: true, message: "结束时间不能为空", trigger: "change" }],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 按钮loading状态
const exportLoading = ref(false);
const fileUploadRef = ref(null);

/** 下载附件 */
const handleFileDownload = (file) => {
  downloadFile(file)
}

const normalizeFileObjectsForUpload = (files) => {
  if (!files) return [];
  let list = [];
  if (typeof files === "string") {
    list = files
      .split(",")
      .map((item) => item.trim())
      .filter(Boolean);
  } else if (Array.isArray(files)) {
    list = files;
  } else {
    return [];
  }

  const timestamp = Date.now();
  return list.map((file, index) => {
    if (typeof file === "string") {
      return {
        name: getFileNameFromPath(file),
        url: file,
        uid: `${timestamp}-${index}`,
      };
    }
    return {
      name: file.name || file.fileName || getFileNameFromPath(file.filePath || file.url || ""),
      url: file.url || file.filePath || "",
      uid: file.uid || `${timestamp}-${index}`,
    };
  });
};

const buildFileObjectsPayload = () => {
  const currentFileList = fileUploadRef.value?.fileList || [];
  if (currentFileList.length) {
    return currentFileList
      .filter((item) => item.url || item.response?.url)
      .map((item) => {
        const filePath = item.url || item.response?.url || "";
        return {
          filePath,
          fileName: getFileNameFromPath(item.name || item.fileName || filePath),
        };
      });
  }

  const normalized = normalizeFileObjectsForUpload(form.value.fileObjects);
  return normalized
    .filter((item) => item.url)
    .map((item) => ({
      filePath: item.url,
      fileName: getFileNameFromPath(item.name || item.url),
    }));
};

/** 查询列表 */
function handleGetList() {
  loading.value = true;
  getList(queryParams.value)
    .then((res) => {
      loading.value = false;
      // 如果接口返回成功且有数据，则展示数据
      if (res.code === 200 && res.rows && res.rows.length > 0) {
        list.value = res.rows;
      total.value = res.total || 0;
      } else {
        // 接口返回为空或失败，不展示任何内容
        list.value = [];
        total.value = 0;
      }
    })
    .catch(() => {
      // 接口报错，不展示任何内容
      loading.value = false;
      list.value = [];
      total.value = 0;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  handleGetList();
}

function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    yearNum: undefined,
  };
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + id + '"的数据项？')
    .then(function () {
      return delItem(id);
    })
    .then(() => {
      handleGetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  exportLoading.value = true;
  try {
    proxy.download(
      "biz/system/enrollTime/export",
      {
        ...queryParams.value,
      },
      `sign_time_${new Date().getTime()}.xlsx`
    );
  } finally {
    // 设置延迟，确保用户能看到loading效果
    setTimeout(() => {
      exportLoading.value = false;
    }, 1000);
  }
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = getDefaultForm();
  proxy.resetForm("formRef");
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加报名时间";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getDetail(id)
    .then((res) => {
      form.value = {
        ...getDefaultForm(),
        ...(res.data || {}),
      };
      form.value.fileObjects = normalizeFileObjectsForUpload(
        res.data?.fileObjects || []
      );
      open.value = true;
      title.value = "修改报名时间";
    })
    .catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      const fileObjects = buildFileObjectsPayload();
      const payload = {
        ...form.value,
        fileObjects,
      };
      if (form.value.id != undefined) {
        editItem(payload)
          .then(() => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            handleGetList();
          })
          .catch(() => {});
      } else {
        addItem(payload)
          .then(() => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            handleGetList();
          })
          .catch(() => {});
      }
    }
  });
}

handleGetList();
</script>

